const axios = require("axios");
const cheerio = require("cheerio");
const url = require("url");
const fs = require("fs");
const path = require("path");
const mainurl = "http://www.zxcs8.com/";
(async () => {
  let webres = await axios.get("http://www.zxcs8.com/").catch(error => {
    // console.error("错误", error);
    console.log("访问出错.........");
  });
  if (webres.statusText == "OK") {
    console.log("访问中.........");
    const $ = cheerio.load(webres.data);
    const list = $(".mlist .box ul li a")
      .map((i, elem) => {
        if ($(elem).text() !== "知轩藏书") {
          return {
            TxTname: $(elem).text(),
            TxtId: getBookid($(elem).attr("href"))
          };
        }
      })
      .get();
    console.log("获取首页全部书籍成功");
    for (let i = 0; i < list.length; i++) {
      const downloadpage = await axios.get(
        "http://www.zxcs8.com/download.php?id=" + list[i].TxtId
      );
      const html_download = cheerio.load(downloadpage.data);
      const ddname = html_download(".downfile a").get(0);
      console.log(`正在下载${list[i].TxTname}....`);
      const dl = await downloadBooke($(ddname).attr("href"));
      const ws = fs.createWriteStream(
        path.join(`./book`, `${list[i].TxTname}.rar`.trim())
      );
      dl.data.pipe(ws);
    }
  }
})();


function getBookid(_url) {
  if (!_url) {
    console.error("params is null");
  }

  const reg = /post\/(\d+)/i;
  const url_obj = url.parse(_url);
  const bookpath = url_obj.pathname; //'/post/11028'
  return reg.exec(bookpath)[1];
}

function downloadBooke(_url) {
  return axios({
    method: "get",
    url: _url, //'http://d3.zxcs1.xyz/201803/zmzc,xbm.rar',
    responseType: "stream"
  });
}
